package com.sample.generator.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FileOutputStreamProvider implements OutputStreamProvider {

	public OutputStream open(String name) throws IOException {

		if (name == null) {
			throw new IllegalArgumentException("Argument name is null.");
		}
		String canonicalPath = new File(name).getCanonicalPath();
		File file = createFile(canonicalPath);
		return new FileOutputStream(file);
	}

	private File createFile(String path) throws IOException {

		File file = new File(path);

		File parent = file.getParentFile();
		if (parent != null && !parent.exists()) {
			parent.mkdirs();
		}
		if (!file.exists()) {
			file.createNewFile();
		}
		if (!file.isFile()) {
			throw new IllegalArgumentException("Specified path '" + path
					+ "'doesn't point to File. ");
		}
		return file;
	}
}
